//
//  FighterMoveBezierByAction.cpp
//  airfight
//
//  Created by aaron more on 12-9-27.
//  Copyright (c) 2012年 moonriver. All rights reserved.
//

#include <iostream>
#include "FighterMoveBezierThreeByAction.h"

static inline float bezierThreeTrack( float a, float b, float c, float d, float t )
{
    return (powf(1-t,3) * a + 
            3*t*(powf(1-t,2))*b + 
            3*powf(t,2)*(1-t)*c +
            powf(t,3)*d );
}

FighterMoveBezierThreeByAction* FighterMoveBezierThreeByAction::create(Move* p_move)
{
    FighterMoveBezierThreeByAction *pBezierBy = new FighterMoveBezierThreeByAction();
    ccBezierConfig bezierConfig;
    CCArray* controls = p_move->getControls();
    bezierConfig.controlPoint_1 = ((Control*)controls->objectAtIndex(0))->getControlPoint();
    bezierConfig.controlPoint_2 = ((Control*)controls->objectAtIndex(1))->getControlPoint();
    bezierConfig.endPosition = p_move->getEndPoint();
    
    pBezierBy->initWithDuration(p_move->getDuration(), bezierConfig);
    pBezierBy->autorelease();
    return pBezierBy;
}

void FighterMoveBezierThreeByAction::startWithTarget(CCNode *pTarget)
{
    CCActionInterval::startWithTarget(pTarget);
    m_startPosition = pTarget->getPosition();
}


bool FighterMoveBezierThreeByAction::initWithDuration(float duration, const ccBezierConfig& c)
{
    if (CCActionInterval::initWithDuration(duration))
    {
        m_sConfig = c;
        return true;
    }
    
    return false;
}


void FighterMoveBezierThreeByAction::update(float time)
{
    if (m_pTarget)
    {
        float xa = 0;
        float xb = m_sConfig.controlPoint_1.x;
        float xc = m_sConfig.controlPoint_2.x;
        float xd = m_sConfig.endPosition.x;
        
        float ya = 0;
        float yb = m_sConfig.controlPoint_1.y;
        float yc = m_sConfig.controlPoint_2.y;
        float yd = m_sConfig.endPosition.y;
        
        float x = bezierThreeTrack(xa, xb, xc, xd, time);
        float y = bezierThreeTrack(ya, yb, yc, yd, time);
        m_pTarget->setPosition(ccpAdd(m_startPosition, ccp(x, y)));
    }
}

